import asyncio
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
from collections import deque

from .stream_executor import streamCommandExecutor, StreamingResult
from .config_manager import HostConfig
from .ssh_connection import SSHManager

class RealtimeDisplay:
    """实时输出显示器"""
    
    def __init__(self, console: Console):
        self.console = console
        self.displays = {}  # 每个命令的显示缓冲区
        
    def create_stream_display(self, host_name: str, command: str, max_lines: int = 20):
        """为流式命令创建显示区域"""
        key = f"{host_name}:{command}"
        self.displays[key] = {
            'lines': deque(maxlen=max_lines),
            'title': f"[{host_name}] {command[:50]}...",
            'is_active': True
        }
        return key
    
    def update_stream_output(self, display_key: str, line: str):
        """更新流式输出"""
        if display_key in self.displays:
            self.displays[display_key]['lines'].append(line)
    
    def render_all_streams(self) -> Panel:
        """渲染所有活跃的流式输出"""
        if not self.displays:
            return Panel("没有活跃的流式命令", title="实时输出")
        
        content = []
        for key, display in self.displays.items():
            if display['is_active'] and display['lines']:
                content.append(f"[bold]{display['title']}[/bold]")
                for line in list(display['lines'])[-10:]:  # 只显示最后10行
                    content.append(f"  {line}")
                content.append("")  # 空行分隔
        
        return Panel("\n".join(content), title="实时输出", border_style="green")

# 使用示例
async def demo_streaming_execution():
    """演示流式命令执行"""
    console = Console()
    display = RealtimeDisplay(console)
    # 假设我们有一个SSH连接管理器
    ssh_manager = ...  # 实际使用时需要初始化
    host_config = ...  # 主机配置
    
    async def output_callback(line: str, result):
        """实时输出回调"""
        display_key = f"{result.host_name}:{result.command}"
        display.update_stream_output(display_key, line)
    
    # 在Live显示中展示实时输出
    with Live(display.render_all_streams(), refresh_per_second=2) as live:
        # 执行流式命令
        executor = streamCommandExecutor(ssh_manager)
        
        display_key = display.create_stream_display("server1", "tail -f /var/log/syslog")
        
        result = await executor.execute_streaming_command(
            host=host_config,
            command="tail -f /var/log/syslog",
            max_duration=60,
            output_callback=output_callback
        )
        
        # 更新显示
        live.update(display.render_all_streams())